package net.wicp.tams.common.connector.executor.busi;

import java.net.URLClassLoader;

import org.apache.commons.lang3.ArrayUtils;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Plugin;
import net.wicp.tams.common.connector.executor.IBusiApp;
import net.wicp.tams.common.connector.executor.IBusiManager;

@Slf4j
public class ClassLoadManager implements IBusiManager {

	private Plugin plugin;

	private final String dirpath;
	private final int maxLevel;
	private final String[] packageBases;

	/****
	 * 
	 * @param dirpath
	 *            插件所在目录
	 * @param maxLevel
	 *            需要寻找几层目录的jar包
	 * @param packageBases
	 *            需要寻找哪些包
	 */
	public ClassLoadManager(String dirpath, int maxLevel, String... packageBases) {
		this.dirpath = dirpath;
		this.maxLevel = maxLevel;
		this.packageBases = packageBases;
		init();
	}

	private void init() {
		this.plugin = new Plugin(this.dirpath, "net.wicp.tams.common.connector.executor.IBusiApp",
				IBusiApp.class.getClassLoader(), this.maxLevel);
	}

	@Override
	public IBusiApp getBean(String appKey) {
		if (ArrayUtils.isNotEmpty(packageBases)) {
			for (String packageBase : packageBases) {
				String formatestr = packageBase.endsWith(".") ? "%s%s" : "%s.%s";
				String className = String.format(formatestr, packageBase, appKey);
				try {
					Class<?> classz = plugin.loadSingleByClassName(className);
					IBusiApp retobj = (IBusiApp) classz.newInstance();
					return retobj;
				} catch (Exception e) {
					log.error("{}未找到{}", packageBase, appKey);
				}
			}
		}
		return null;
	}

	@Override
	public void refresh() {
		this.plugin.close();
		init();
	}

	public URLClassLoader getCloasLoader() {
		URLClassLoader classLoader = this.plugin.getLoad().getClassLoader();
		return classLoader;
	}
}
